<template>
    <div>
        <!-- 商品列表展示区域 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="content-padding">
                    <!-- 标题栏 -->
                    <div class="flex">
                        <div class="name-column">名称</div>
                        <div class="time-top">创建时间</div>
                    </div>
                    
                    <!-- 搜索和筛选区域 -->
                    <div class="flexBox">
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入名称/分类名称"
                                    class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div class="filter-margin">
                            <el-date-picker class="date-picker" @change="data_filters" v-model="time" type="daterange"
                                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    
                    <!-- 操作按钮区域 -->
                    <div class="action-buttons">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>
                    
                    <!-- 商品列表表格 -->
                    <div> 
                        <el-table :data="displayList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                                class="goods-table" :cell-style="{ 'text-align': 'center' }" lazy="true"
                                v-el-table-infinite-scroll="handleTableScroll"
                                :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" width="120" />
                            <el-table-column prop="title" label="名称" show-overflow-tooltip width="120" />
                            <el-table-column prop="classname" label="分类名称" show-overflow-tooltip width="150" />
                            <el-table-column prop="content" label="简介" show-overflow-tooltip width="150" />
                            <el-table-column prop="price" sortable label="价格" show-overflow-tooltip width="150" />
                            <el-table-column prop="userImg" label="图片" width="120">
                                <template #default="scope">
                                    <div class="demo-image__preview">
                                        <el-image class="preview-image" :src="testName + scope.row.img"
                                                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[testName +
                                                    scope.row.img]" :initial-index="4" fit="cover" preview-teleported />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="商品状态" width="120">
                                <template #default="scope">
                                    <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                                            @change="handleStatusChange(scope.row)" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="createtime" label="创建时间" width="190">
                                <template #default="scope">
                                    {{ new Date(scope.row.createtime).toLocaleString() }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="150" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)"
                                            class="edit-action">编辑</div>
                                        <div class="action-spacing"></div>
                                        <div @click="deletes(scope.row)" class="delete-action">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                                :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                                layout="total, sizes, prev, pager, next, jumper" :total="displayList.length" />
                    </div>
                    
                    <!-- 单个删除确认对话框 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该数据吗?</div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                    
                    <!-- 旧的删除确认对话框(未使用) -->
                    <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                        <el-button @click="shows = false">取 消</el-button>
                        <el-button type="primary" @click="oks">确 定</el-button>
                    </el-dialog>
                    
                    <!-- 批量删除确认对话框 -->
                    <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                        <div class="dialog-message">确认删除这批数据吗?</div>
                        <span slot="footer" class="dialog-footer">
                            <div></div>
                            <div>
                                <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                                <el-button type="primary" @click="deleteid_t">确 定</el-button>
                            </div>
                        </span>
                    </el-dialog>
                </div>
            </el-card>
        </div>

        <!-- 商品编辑/新增表单区域 -->
        <div v-show="activeStatud" class="form-container">
            <el-card class="form-card">
                <div class="form-title">{{ addText }}</div>
                <div class="divider"></div>
                
                <!-- 表单区域 -->
                <div class="form-content">
                    <el-form ref="ruleFormRef" class="form-wrapper" :model="ruleForm" status-icon :rules="rules"
                            label-position="left" label-width="auto">
                        <div class="form-row">
                            <!-- 左侧表单区域 -->
                            <div class="form-column">
                                <el-form-item label="商品名称" prop="title" class="form-item">
                                    <el-input v-model.trim="ruleForm.title" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="商品分类" prop="type" class="form-item">
                                    <el-select v-model="ruleForm.type" placeholder="请选择" class="full-width-input">
                                        <el-option v-for="item in optioned" :key="item.value" :label="item.label"
                                                :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="商品排序" prop="sort" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseSort">-</button>
                                        <input type="text" v-model="ruleForm.sort" @input="handleSortInput"
                                                @blur="validateSortInput" placeholder="" />
                                        <button type="button" @click="increaseSort">+</button>
                                    </div>
                                </el-form-item>
                                <el-form-item prop="imgs" label="商品轮播" class="carousel-upload">
                                    <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                            v-model="ruleForm.imgs" :on-preview="handlePictureCardPreview"
                                            :on-remove="handleRemove" :file-list="fileList" :on-change="handleChange"
                                            :on-success="handleSuccess" :before-upload="beforeUpload" :auto-upload="false"
                                            :limit="5" :on-exceed="handleExceed">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                            </div>
                            
                            <!-- 右侧表单区域 -->
                            <div class="form-column right-column">
                                <el-form-item label="商品价格" prop="price" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreasePrice">-</button>
                                        <input type="text" v-model="ruleForm.price" @input="handlePriceInput"
                                                @blur="validatePriceInput" placeholder="" />
                                        <button type="button" @click="increasePrice">+</button>
                                    </div>
                                </el-form-item>
                                <el-form-item label="商品售量" prop="quantity" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseQuantity">-</button>
                                        <input type="text" v-model="ruleForm.quantity" @input="handleQuantityInput"
                                                @blur="validateQuantityInput" placeholder="" />
                                        <button type="button" @click="increaseQuantity">+</button>
                                    </div>
                                </el-form-item>
                                <el-form-item label="商品好评" prop="good_reviews" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseGoodReviews">-</button>
                                        <input type="text" v-model="ruleForm.good_reviews"
                                                @input="handleGoodReviewsInput" @blur="validateGoodReviewsInput"
                                                placeholder="" />
                                        <button type="button" @click="increaseGoodReviews">+</button>
                                    </div>
                                </el-form-item>
                                <el-form-item label="商品库存" prop="stock" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseStock">-</button>
                                        <input type="text" v-model="ruleForm.stock" @input="handleStockInput"
                                                @blur="validateStockInput" placeholder="" />
                                        <button type="button" @click="increaseStock">+</button>
                                    </div>
                                </el-form-item>
                                <el-form-item prop="img" label="商品封面" class="form-item">
                                    <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                            v-model='ruleForm.img' :on-preview="handlePictureCardPreviewt"
                                            :on-remove="handleRemovet" :file-list="fileListt"
                                            :before-upload="beforeAvatarUploadt">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                            </div>
                        </div>

                        <!-- 商品介绍富文本编辑器 -->
                        <el-form-item label="商品介绍" prop="content" class="full-width-item">
                            <vue-ueditor-wrap v-model="ruleForm.content" :config="editorConfig"
                                    editor-id="editor-demo-01"></vue-ueditor-wrap>
                        </el-form-item>
                    </el-form>
                    
                    <!-- 表单操作按钮 -->
                    <div class="form-actions">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
        
        <!-- 图片预览对话框 -->
        <el-dialog v-model="dialogVisiblet">
            <img class="preview-full-image" :src="dialogImageUrlt" alt="Preview Image" />
        </el-dialog>
        <el-dialog v-model="dialogVisible">
            <img class="preview-full-image" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { score_goodsList, score_goodsSave, score_goodsDel } from '../../../api/shopGood/index';
import { typeList } from '../../../api/shopClass/index';
import { ElMessage, ElCard, ElDropdown } from 'element-plus';
import { Plus, Search, ArrowLeft, ArrowDown, RefreshRight, Sort } from '@element-plus/icons-vue';
import { scenicUpload } from '../../../api/uploading/index';
import { useRoute, useRouter } from 'vue-router';

// 日期范围选择器绑定值
const time = ref('')

// 数据管理
const originalList = ref([]); // 存储原始数据
const displayList = computed(() => { // 计算属性用于显示过滤后的数据
    if (!inputed.value && !time.value) return originalList.value;

    return originalList.value.filter(item => {
        const nameMatch = item.title?.includes(inputed.value) || item.classname?.includes(inputed.value);
        const timeMatch = !time.value || (
            item.createtime >= new Date(time.value[0]).getTime() &&
            item.createtime <= new Date(time.value[1]).getTime()
        );

        return nameMatch && timeMatch;
    });
});

// 视图控制
const activeStatu = ref(true)  // 控制列表视图显示
const activeStatud = ref(false) // 控制表单视图显示
const dialogVisiblet = ref(false) // 图片预览对话框
const dialogVisible = ref(false); // 图片预览对话框
const fileList = ref([]); // 轮播图文件列表
const dialogImageUrlt = ref(''); // 预览图片URL
const names = ref('导出');
const dialogImageUrl = ref(''); // 预览图片URL

// 全局注入的函数和变量
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')

// 表格和分页控制
const dialogTableVisible = ref(false);
const statused = ref('1');
const router = useRouter();
const inputed = ref(''); // 搜索关键词
const inputeds = ref('');
const pageSize = ref(5); // 每页显示数量
const currentPage = ref(1); // 当前页码
const pageSizes = ref(5);
const currentPages = ref(1);
const copyList = ref([]);
const files = ref(false);
const synopsiss = ref('请输入简介')

// 分类数据和激活ID
const optioned = ref([]) // 商品分类列表
const activId = ref('')

// 从本地存储获取token
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);

// 价格输入处理函数
const sanitizePriceInput = (value) => {
    if (value === null || value === undefined || isNaN(value)) {
        ruleForm.value.price = 0;
        return;
    }

    // 转为整数
    const numValue = Number(value);
    ruleForm.value.price = Math.max(0, Math.floor(numValue));
};

// 格式化价格显示
const formatPrice = () => {
    if (isNaN(ruleForm.value.price)) {
        ruleForm.value.price = 0;
    }
};

// 初始化渲染数据
render();
async function render() {
    try {
        // 并行请求商品列表和分类列表
        const [goodsRes, typeRes] = await Promise.all([
            score_goodsList(),
            typeList()
        ]);

        console.log('商品列表:', goodsRes);
        originalList.value = goodsRes.data || [];

        console.log('分类列表:', typeRes);
        optioned.value = typeRes.data?.map(item => ({
            value: item.id,
            label: item.title
        })) || [];
    } catch (error) {
        console.error('数据加载失败:', error);
        ElMessage.error('数据加载失败，请重试');
    }
}

// 表单初始值
const ruleForms = reactive({
    type: '',
    title: '',
    img: '',
    imgs: [],
    content: '',
    price: '',
    good_reviews: '',
    stock: '',
    quantity: '',
    status: 1,
    sort: ''
})

// 图片和状态管理
const list = ref([])
const lists = ref([])
const fileImg = ref([])
const Delete = ref('')
const fileListst = ref([])
const fileListQW = ref([])
// 照片移除后的数据
const fileremover = ref([])
const fileListqq = ref([])
const status = ref('1')
const iitimg = ref([])

// 富文本编辑器配置
const editorConfig = reactive({
    // 编辑器不自动被内容撑高
    autoHeightEnabled: false,
    // 初始容器高度
    initialFrameHeight: 150,
    // 初始容器宽度
    initialFrameWidth: '100vw',
    UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径
    serverUrl: '/pc/common/ueditor', // 服务端接⼝
    uploadUrl: '/UEditor',
});

// 处理商品状态变更
const handleStatusChange = async (row) => {
    // 构造请求参数
    const requestData = {
        ...row,          // 展开当前行所有数据
        status: row.status // 自动映射为0或1
    };

    try {
        const res = await score_goodsSave(requestData);
        console.log('状态更新响应:', res);

        if (res.code == '1') {
            ElMessage.success(row.status === 0 ? '已上架' : '已下架');

            // 更新原始列表中的状态
            const index = originalList.value.findIndex(item => item.id === row.id);
            if (index !== -1) {
                originalList.value[index].status = row.status;
            }
        } else {
            // 失败时回滚状态
            row.status = row.status === 0 ? 1 : 0;
            ElMessage.error(res.message || '状态更新失败');
        }
    } catch (error) {
        row.status = row.status === 0 ? 1 : 0; // 网络错误时回滚
        ElMessage.error('请求失败');
    }
};

// 封面图片预览
const fileListt = ref([]);
const handlePictureCardPreviewt = (file) => {
    dialogImageUrlt.value = file.url;
    dialogVisiblet.value = true;
}

// 封面图片移除
const handleRemovet = (file, fileListt) => {
    console.log(file, fileListt);
};

// 图片超出限制处理
const handleExceed = (files, fileList) => {
    ElMessage.warning('最多只能上传5张图片');
};

// 封面图片上传前处理
const beforeAvatarUploadt = (file) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))

    const formData = new FormData();
    formData.append('file', file);
    console.log(formData);
    
    // 异步上传图片
    scenicUpload(formData).then(res => {
        console.log(res);

        // 更新文件列表和表单数据
        fileListt.value = [{
            url: testName + res.data.url,
        }]
        ruleForm.img = res.data.url
    })

    return false; // 阻止默认上传行为
}

// 轮播图预览
const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}

const imgList = ref([])

// 轮播图上传变更处理
const handleChange = (file, fileLists) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    
    // 验证文件类型
    if (
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
    ) {
        const formData = new FormData();
        formData.append('file', file.raw);
        
        // 异步上传图片
        scenicUpload(formData).then(res => {
            console.log(res.code);
            if (res.code == 1) {
                ruleForm.imgs = res.data.url
                console.log(res.data, '上传成功');
                fileImg.value.push(res.data.url)
                fileremover.value.push(res.data.url)
                imgList.value.push(res.data.url.split(','))
                iitimg.value.push(res.data.url)
            }
        })
    } else {
        ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
        return false
    }
    console.log(file);
    console.log(file.raw);
};

// 轮播图上传成功回调
const handleSuccess = (response, file, fileList) => {
    console.log('File uploaded successfully:', response, file, fileList);
    console.log(fileImg.value);
};

// 轮播图上传前验证
const beforeUpload = (rawFile) => {
    console.log(rawFile);

    if (fileList.value.length >= 5) {
        ElMessage.warning('最多只能上传5张图片');
        return false;
    }
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

// 轮播图移除处理
const handleRemove = (uploadFile, uploadFiles) => {
    const formData = new FormData();
    formData.append('file', uploadFile.raw);
    
    // 上传已移除的图片信息（可能用于删除服务器文件）
    scenicUpload(formData).then(res => {
        console.log(res.data.url);
        // 从图片列表中移除
        for (let i = 0; i < iitimg.value.length; i++) {
            if (iitimg.value[i] == res.data.url) {
                iitimg.value.splice(i, 1)
                break;
            }
        }
    })
}

// 获取当前日期时间字符串
function getCurrentDateTimeString() {
    const now = new Date();
    // 获取当前的年份，并只取后两位
    const year = now.getFullYear().toString().slice();
    // 获取当前的月份，并确保是两位数（从0开始）
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    // 获取当前的日期，并确保是两位数
    const day = now.getDate().toString().padStart(2, '0');
    // 获取当前的小时，并确保是两位数
    const hours = now.getHours().toString().padStart('0');
    // 获取当前的分钟，并确保是两位数
    const minutes = now.getMinutes().toString().padStart(2, '0');
    // 获取当前的秒，并确保是两位数
    const seconds = now.getSeconds().toString().padStart(2, '0');
    // 拼接成所需的字符串格式
    const dateTimeString = `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
    g = `${year}-${month}-${day}`
    return dateTimeString;
}

// 新增商品
const addText = ref("")
function add() {
    // 重置表单数据
    Object.assign(ruleForm, ruleForms)
    fileList.value = []
    fileListst.value = []
    fileListt.value = []
    
    // 切换视图到表单
    activeStatu.value = false
    addText.value = '添加'
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
}

// 表单数据和验证规则
const ruleForm = reactive({
    type: '',
    title: '',
    img: '',
    imgs: [],
    content: '',
    price: '',
    good_reviews: '',
    stock: '',
    quantity: '',
    status: 1,
    sort: ''
});

const ruleFormRef = ref('');
const rules = reactive({
    title: [
        {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
        },
    ],
    type: [
        {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'blur',
        },
    ],
    imgs: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'blur',
        },
    ],
    price: [
        {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur',
        },
    ],
    stock: [
        {
            required: true,
            message: '请输入库存',
            trigger: 'blur',
        },
    ],
    good_reviews: [
        {
            required: true,
            message: '请输入好评率',
            trigger: 'blur',
        },
    ],
    content: [
        {
            required: true,
            message: '请输入详细介绍',
            trigger: 'blur',
        },
    ],
    quantity: [
        {
            required: true,
            message: '请输入售量',
            trigger: 'blur',
        },
    ],
    sort: [
        {
            required: true,
            message: '请输入排序',
            trigger: 'blur',
        },
    ],
});

// 邮箱域名验证函数（未使用）
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

const imgUrls = ref('');

// 提交表单
const submitForm = (formEl) => {
    console.log(ruleForm);
    if (!formEl) return;
    
    // 表单验证
    formEl.validate((valid) => {
        if (valid) {
            if (statused.value == '1') {
                // 新增操作
                console.log(ruleForm);
                score_goodsSave(ruleForm).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    }
                });
            } else if (statused.value == '2') {
                // 编辑操作
                ruleForm.id = ids.value
                score_goodsSave(ruleForm).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    } else {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    }
                });
            }
        }
        else {
            ElMessage({
                message: '新增失败',
                type: 'error',
            });
        }
    });
};

// 数量减少按钮处理
const decreaseQuantity = () => {
    if (ruleForm.quantity && parseInt(ruleForm.quantity) > 1) {
        ruleForm.quantity = (parseInt(ruleForm.quantity) - 1).toString();
    }
};

// 数量增加按钮处理
const increaseQuantity = () => {
    if (ruleForm.quantity) {
        ruleForm.quantity = (parseInt(ruleForm.quantity) + 1).toString();
    } else {
        ruleForm.quantity = '1';
    }
};

// 价格减少按钮处理
const decreasePrice = () => {
    if (ruleForm.price && parseFloat(ruleForm.price) > 0.01) {
        ruleForm.price = (parseFloat(ruleForm.price) - 0.01).toFixed(2);
    }
};

// 价格增加按钮处理
const increasePrice = () => {
    if (ruleForm.price) {
        ruleForm.price = (parseFloat(ruleForm.price) + 0.01).toFixed(2);
    } else {
        ruleForm.price = '0.01';
    }
};

// 好评数减少按钮处理
const decreaseGoodReviews = () => {
    if (ruleForm.good_reviews && parseInt(ruleForm.good_reviews) > 0) {
        ruleForm.good_reviews = (parseInt(ruleForm.good_reviews) - 1).toString();
    }
};

// 好评数增加按钮处理
const increaseGoodReviews = () => {
    if (ruleForm.good_reviews) {
        ruleForm.good_reviews = (parseInt(ruleForm.good_reviews) + 1).toString();
    } else {
        ruleForm.good_reviews = '0';
    }
};

// 库存减少按钮处理
const decreaseStock = () => {
    if (ruleForm.stock && parseInt(ruleForm.stock) > 0) {
        ruleForm.stock = (parseInt(ruleForm.stock) - 1).toString();
    }
};

// 库存增加按钮处理
const increaseStock = () => {
    if (ruleForm.stock) {
        ruleForm.stock = (parseInt(ruleForm.stock) + 1).toString();
    } else {
        ruleForm.stock = '0';
    }
};

// 排序减少按钮处理
const decreaseSort = () => {
    if (ruleForm.sort && parseInt(ruleForm.sort) > 0) {
        ruleForm.sort = (parseInt(ruleForm.sort) - 1).toString();
    }
};

// 排序增加按钮处理
const increaseSort = () => {
    if (ruleForm.sort) {
        ruleForm.sort = (parseInt(ruleForm.sort) + 1).toString();
    } else {
        ruleForm.sort = '0';
    }
};

// 数量验证函数
const validateQuantity = (rule, value, callback) => {
    const reg = /^[1-9]\d*$/;

    if (!value) {
        callback(new Error('请输入售量'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的正整数'));
    } else {
        callback();
    }
};

// 价格验证函数
const validatePrice = (rule, value, callback) => {
    const reg = /^\d+(\.\d{1,2})?$/;

    if (!value) {
        callback(new Error('请输入价格'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入有效的价格（最多两位小数）'));
    } else if (parseFloat(value) <= 0) {
        callback(new Error('价格必须大于0'));
    } else {
        callback();
    }
};

// 好评数验证函数
const validateGoodReviews = (rule, value, callback) => {
    const reg = /^\d+$/;

    if (!value) {
        callback(new Error('请输入好评数'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入有效的整数'));
    } else {
        callback();
    }
};

// 库存验证函数
const validateStock = (rule, value, callback) => {
    const reg = /^\d+$/;

    if (!value) {
        callback(new Error('请输入库存'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入有效的整数'));
    } else {
        callback();
    }
};

// 排序验证函数
const validateSort = (rule, value, callback) => {
    const reg = /^\d+$/;

    if (!value) {
        callback(new Error('请输入排序'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入有效的整数'));
    } else {
        callback();
    }
};

// 数量输入处理
const handleQuantityInput = (event) => {
    let value = event.target.value;
    value = value.replace(/[^0-9]/g, '');

    if (value.startsWith('0') && value.length > 1) {
        value = value.substring(1);
    }

    ruleForm.quantity = value;
};

// 价格输入处理
const handlePriceInput = (event) => {
    let value = event.target.value;
    value = value.replace(/[^0-9.]/g, '');

    // 确保只有一个小数点
    const decimalIndex = value.indexOf('.');
    if (decimalIndex !== -1) {
        value = value.substring(0, decimalIndex + 3); // 保留两位小数
    }

    // 不允许前导零（除非是0.xx）
    if (value.startsWith('0') && value.length > 1 && value[1] !== '.') {
        value = value.substring(1);
    }

    ruleForm.price = value;
};

// 好评数输入处理
const handleGoodReviewsInput = (event) => {
    let value = event.target.value;
    value = value.replace(/[^0-9]/g, '');

    ruleForm.good_reviews = value;
};

// 库存输入处理
const handleStockInput = (event) => {
    let value = event.target.value;
    value = value.replace(/[^0-9]/g, '');

    ruleForm.stock = value;
};

// 排序输入处理
const handleSortInput = (event) => {
    let value = event.target.value;
    value = value.replace(/[^0-9]/g, '');

    ruleForm.sort = value;
};

// 数量失焦验证
const validateQuantityInput = () => {
    const value = ruleForm.quantity;
    const reg = /^[1-9]\d*$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0的正整数'
        });
        ruleForm.quantity = '';
    }
};

// 价格失焦验证
const validatePriceInput = () => {
    const value = ruleForm.price;
    const reg = /^\d+(\.\d{1,2})?$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入有效的价格（最多两位小数）'
        });
        ruleForm.price = '';
    } else if (value && parseFloat(value) <= 0) {
        ElMessage({
            type: 'warning',
            message: '价格必须大于0'
        });
        ruleForm.price = '';
    }
};

// 好评数失焦验证
const validateGoodReviewsInput = () => {
    const value = ruleForm.good_reviews;
    const reg = /^\d+$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入有效的整数'
        });
        ruleForm.good_reviews = '';
    }
};

// 库存失焦验证
const validateStockInput = () => {
    const value = ruleForm.stock;
    const reg = /^\d+$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入有效的整数'
        });
        ruleForm.stock = '';
    }
};

// 排序失焦验证
const validateSortInput = () => {
    const value = ruleForm.sort;
    const reg = /^\d+$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入有效的整数'
        });
        ruleForm.sort = '';
    }
};

// 当前编辑的商品ID
const ids = ref('');
const disableds = ref(true);

// 关闭表单
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.img = ''
    ruleForm.imgs = []
    fileListt.value = []
    fileList.value = []
};

// 编辑商品
function edit(item) {
    // 填充表单数据
    Object.assign(ruleForm, item);
    addText.value = '编辑'
    ids.value = item.id;
    
    // 切换视图到表单
    activeStatud.value = true
    activeStatu.value = false
    ruleForm.name = item.title

    disableds.value = false;
    statused.value = '2';

    // 初始化封面图片
    fileListt.value = [{
        url: testName + item.img,
    }]
    
    // 初始化轮播图片
    for (let i = 0; i < item.imgs.split(',').length; i++) {
        console.log(item.imgs.split(','));
        fileListQW.value.push(testName + item.imgs.split(',')[i])
        fileList.value.push(
            {
                url: testName + item.imgs.split(',')[i],
            });
    }
}

// 删除单个商品
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

// 删除操作相关变量
const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除单个商品
async function deleteid() {
    try {
        const res = await score_goodsDel({ ids: deleteids.value });
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage.success('删除成功');
            render();
        }
    } catch (error) {
        ElMessage.error('删除失败，请重试');
    }
}

// 分类名称搜索
function filters() {
    currentPage.value = 1;
    console.log('搜索关键词:', inputed.value);
    // 搜索逻辑已由computed属性处理
}

// 分类日期搜索
function data_filters() {
    currentPage.value = 1;
    console.log('搜索日期范围:', time.value);
    // 日期过滤逻辑已由computed属性处理
}

// 批量删除相关
const shows = ref(false);
const setArr = ref([]);
const multipleTableRef = ref()
const SelectArr = ref([])
const All_Delete = ref([])

// 表格选择变化处理
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的数据',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
async function deleteid_t() {
    try {
        const res = await score_goodsDel({
            ids: st.value.join(','),
        });

        console.log('批量删除响应:', res);
        centerDialogVisiblet.value = false;
        render();
        ElMessage.success('删除成功');
    } catch (error) {
        ElMessage.error('删除失败，请重试');
    }
}
</script>

<style>
/* 基础样式 */
.text {
    font-size: 14px;
}

/* 间距和布局 */
.content-padding {
    padding: 10px;
}

.name-column {
    width: 220px;
}

.time-top {
    /* 保持原有样式 */
}

.flexBox {
    display: flex;
}

.filter-margin {
    margin-left: 20px;
}

.action-buttons {
    display: flex;
}

.add_class {
    /* 保持原有样式 */
}

.delelist {
    /* 保持原有样式 */
}

.goods-table {
    margin-top: 10px;
    width: 100%;
}

.preview-image {
    width: 50px;
    height: 50px;
}

.edit-action {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.delete-action {
    color: red;
    cursor: pointer;
}

.action-spacing {
    width: 10px;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.search-input {
    width: 220px;
}

.date-picker {
    width: 220px;
}

/* 表单区域样式 */
.form-container {
    padding: 10px;
}

.form-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: auto;
}

.form-title {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-content {
    margin-top: 20px;
    margin-left: 100px;
    margin-top: 50px;
}

.form-wrapper {
    width: 100%;
}

.form-row {
    width: 100%;
    display: flex;
}

.form-column {
    width: 48%;
}

.right-column {
    padding-left: 30px;
}

.form-item {
    width: 70%;
}

.full-width-input {
    width: 100%;
}

.full-width-item {
    width: 100%;
    margin-top: 20px;
}

.form-actions {
    margin-top: 10px;
    margin-left: 80%;
}

.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-buttons {
    display: flex;
    justify-content: end;
}

.preview-full-image {
    width: 100%;
    height: 100%;
}

/* Element UI 上传组件样式 */
.el-upload--picture-card {
    --el-upload-picture-card-size: 81px;
    align-items: center;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-flex;
    height: var(--el-upload-picture-card-size);
    justify-content: center;
    vertical-align: top;
    width: var(--el-upload-picture-card-size);
}

/* 轮播图上传区域样式 */
.carousel-upload .el-upload-list--picture-card {
    max-width: 350px;
    --el-upload-list-picture-card-size: 80px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 0;
}

.carousel-upload .el-upload--picture-card {
    --el-upload-picture-card-size: 80px;
    margin: 0;
}

.item {
    margin-bottom: 18px;
}

/* 清除浮动 */
.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

/* 上传列表样式 */
.el-upload-list--picture-card {
    flex-wrap: wrap !important;
    max-width: 350px;
    gap: 8px;
}

.el-picker-panel {
    width: 255px !important;
}

.clearfix:after {
    clear: both;
}

/* 上传图片列表样式 */
.el-upload-list--picture-card {
    --el-upload-list-picture-card-size: 80px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 0;
    max-width: 100%;
}

.el-upload--picture-card {
    --el-upload-picture-card-size: 80px;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

/* 自定义数字输入框样式 */
.custom-number-input {
    display: flex;
    align-items: center;
    width: 120px;
}

.custom-number-input button {
    width: 30px;
    height: 30px;
    border: 1px solid #dcdfe6;
    background-color: #f5f7fa;
    color: #606266;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    user-select: none;
}

.custom-number-input button:hover {
    background-color: #e4e7ed;
}

.custom-number-input button:first-child {
    border-radius: 4px 0 0 4px;
}

.custom-number-input button:last-child {
    border-radius: 0 4px 4px 0;
}

.custom-number-input input {
    flex: 1;
    height: 30px;
    border: 1px solid #dcdfe6;
    border-left: none;
    border-right: none;
    text-align: center;
    padding: 0 5px;
    font-size: 14px;
    outline: none;
    width: 20px;
}

.custom-number-input input:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}
</style>    